<?php
/**
 * Created by PhpStorm.
 * User: reshared
 * Date: 2017/9/28
 * Time: 下午12:58
 */

namespace Index\Controller;


use Index\Repository\UserRepository;
use Think\Controller;

abstract class BaseController extends Controller
{
    /**
     * ajax 返回,json
     * @param int $c
     * @param array $data
     */
    protected function ajaxReturn($c = 10000, $data = array())
    {
        if (is_bool($c)) $c = $c ? 10000 : 10022;
        if (!$c) $c = 10022;
        header('Content-type: application/json');
        echo json_encode(array(
            'c' => $c,
            'm' => C('RET_CODE')[$c],
            'd' => $data
        ));
        die;
    }

    /**
     * 检查是否登录
     */
    protected function checkLogin()
    {
        if (!UserRepository::instance()->hasLogin()) {
            return $this->error('请先登录');
        }
    }

    /**
     * 检查请求方式
     */
    protected function checkPostRequestMethod()
    {
        if(!IS_POST) $this->error("非法请求");
    }

    /**
     * 检查ajax请求方式
     * @param string $method
     */
    protected function checkAjaxRequestMethod($method = 'post')
    {
        if (!IS_AJAX) $this->error("非法请求");
        if ($method == 'post' AND !IS_POST) $this->error("非法请求");
        if ($method == 'get'  AND !IS_GET)  $this->error("非法请求");
        if ($method == 'put'  AND !IS_PUT)  $this->error("非法请求");
        if ($method == 'del'  AND !IS_DELETE)  $this->error("非法请求");
    }

    /**
     * 检查是否含有参数
     * @param $key
     * @param bool $ajax
     */
    protected function hasI($key, $ajax = true)
    {
        if (!is_array($key)) {
            $key = array($key);
        }

        foreach ($key as $k) {
            if (!I($k)) {
                if ($ajax) $this->ajaxReturn(10004);
                $this->error('请将信息填写完全');
            }
        }
    }
}